package com.hoshiicloud.shxping.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hoshiicloud.common.constant.OrderInfoServiceStatusEnum;
import com.hoshiicloud.common.constant.OrderInfoStatusEnum;
import com.hoshiicloud.common.constant.refund.RefundOrderStatusEnum;
import com.hoshiicloud.common.constant.refund.RefundServiceTypeEnum;
import com.hoshiicloud.common.constant.refund.RefundTypeEnum;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.common.utils.BeanUtils;
import com.hoshiicloud.saleorder.entity.Consultations;
import com.hoshiicloud.saleorder.entity.OrderInfo;
import com.hoshiicloud.saleorder.entity.OrderMain;
import com.hoshiicloud.saleorder.entity.RefundOrder;
import com.hoshiicloud.saleorder.param.OrderInfoUpdateParam;
import com.hoshiicloud.saleorder.param.refund.*;
import com.hoshiicloud.saleorder.vo.refund.ApplyAfterSaleInfoVo;
import com.hoshiicloud.saleorder.vo.refund.RefundDetailVo;
import com.hoshiicloud.saleorder.vo.refund.RefundOrderVo;
import com.hoshiicloud.shxping.dto.ConsumerDto;
import com.hoshiicloud.shxping.dto.ExtSpuDto;
import com.hoshiicloud.shxping.dto.MemberDto;
import com.hoshiicloud.shxping.dto.PlatStoreDTO;
import com.hoshiicloud.shxping.feign.GoodsFeignService;
import com.hoshiicloud.shxping.feign.IFileServerFeignClient;
import com.hoshiicloud.shxping.feign.IUserFeignService;
import com.hoshiicloud.shxping.feign.OrderFeignService;
import com.hoshiicloud.shxping.param.RefundPageParam;
import com.hoshiicloud.shxping.service.ShxpRefundOrderService;
import com.hoshiicloud.user.entity.store.PlatStore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 2019/8/28 14:10 qry
 */
@Slf4j
@RestController
@RequestMapping("/refund-order")
@Api(value = "退款管理", tags = {"退款相关操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class ShxpRefundOrderController {


    @Resource
    private ShxpRefundOrderService shxpRefundOrderService;
    @Resource
    private OrderFeignService orderFeignService;
    @Resource
    private IUserFeignService userFeignService;
    @Resource
    private IFileServerFeignClient fileServerFeignClient;
    @Resource
    private GoodsFeignService goodsFeignService;

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation(value = "退款图片上传", notes = "退款图片上传", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response fileUpload(@RequestPart MultipartFile file) {
        String bucketName = "obs-7d37";
        String objectKey = "";
        String fileName = file.getOriginalFilename();
        String folder = "aftersale";
        Boolean privateOwned = false;
        Response response = fileServerFeignClient.uploadFile(file, bucketName, objectKey, fileName, folder, privateOwned);
        return response;
    }


    /**
     * 退款申请
     * @param param 退款參數
     * @return Response
     */

    @PostMapping("/refundApply")
    @ApiOperation(value = "退款申请", notes = "退款申请", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> refundApply(@RequestBody @Valid RefundOrderApplyParam param) {
        Response<OrderInfo> orderInfoRs =  orderFeignService.getOrderInfoById(param.getOrderInfoId());
        if (null == orderInfoRs || orderInfoRs.getCode() != 200 || null == orderInfoRs.getData()) {
            return Response.failed("未获取到子订单信息");
        }
        OrderInfo orderInfo = orderInfoRs.getData();
        Response<OrderMain> orderMainRs =  orderFeignService.getOrderMainById(orderInfoRs.getData().getMainId());
        if (null == orderMainRs || orderMainRs.getCode() != 200 || null == orderMainRs.getData()) {
            return Response.failed("未获取到主订单信息");
        }

        Response<ExtSpuDto> extSpuRs = goodsFeignService.getExtSpuById(orderInfo.getSpuId());
        if (null == extSpuRs || extSpuRs.getCode() != 200 || null == extSpuRs.getData()) {
            return Response.failed("未获取订单内的商品信息");
        }

        Response<ConsumerDto> platConsumerRs = userFeignService.getConsumerById(orderMainRs.getData().getMemberId());
        if (null == platConsumerRs || platConsumerRs.getCode() != 200 || null == platConsumerRs.getData()) {
            return Response.failed("下单消费者不存在");
        }

        Response<PlatStoreDTO> plastStoreRs = userFeignService.queryById(orderMainRs.getData().getStoreId());
        if (null == plastStoreRs || plastStoreRs.getCode() != 200 || null == plastStoreRs.getData()) {
            return Response.failed("下单店铺不存在");
        }
        Response<MemberDto> memberRs = userFeignService.getMemberById(platConsumerRs.getData().getMemberId());
        if (null == memberRs || memberRs.getCode() != 200 || null == memberRs.getData()) {
            return Response.failed("下单消费者不存在");
        }
        int refundType = (orderInfo.getOrderStatus() == OrderInfoStatusEnum.RECEIVED_GOODS .getCode()||
                orderInfo.getOrderStatus() == OrderInfoStatusEnum.EXTRACT_GOODS .getCode()
                )? RefundTypeEnum.AFTER_SALE.getCode(): RefundTypeEnum.IN_SALE.getCode();
        BigDecimal refundMoney = orderInfo.getAmount().divide(new BigDecimal(orderInfo.getQuantity())) .multiply(new BigDecimal(param.getApplyQtys()));
        RefundOrder refundOrder = new RefundOrder();
        refundOrder.setSubId(param.getOrderInfoId());
        refundOrder.setMainId(orderMainRs.getData().getId());
        refundOrder.setMainNo(orderMainRs.getData().getMainNo());
        refundOrder.setOrderNo(orderInfo.getOrderNo());
        refundOrder.setProductTitle(orderInfo.getSpuName());
        refundOrder.setProductImage(extSpuRs.getData().getSpuImage());
        refundOrder.setProductSpec(orderInfo.getSpuExtendSpec());
        refundOrder.setApplyQtys(param.getApplyQtys());
        refundOrder.setRefundAmount(refundMoney);
        refundOrder.setRefundCoines(0L);
        refundOrder.setStatus(RefundOrderStatusEnum.WAIT_SELLER_HANDLE.getCode());
        refundOrder.setServiceType(param.getServiceType());
        refundOrder.setRefundType(refundType);
        refundOrder.setUserId(platConsumerRs.getData().getMemberId());
        //下单点是否分销商 是分销商的话 交给总店处理
        refundOrder.setStoreId( ( 1 == plastStoreRs.getData().getIsDistributor() )? plastStoreRs.getData().getParentId():plastStoreRs.getData().getId());
        refundOrder.setReasons(param.getReasons());
        refundOrder.setRemark(param.getRemark());
        Response<RefundOrder> refundOrderRs = orderFeignService.saveRefundOrder(refundOrder);
        if (null == refundOrderRs || refundOrderRs.getCode() != 200 || null == refundOrderRs.getData()) {
            return Response.failed("新增退款单失败");
        }
        //     * 子订单id ,图1,图2,图3,图4，
        //     * 退款金额，退款数量，退款原因，退款说明
        //     服务类型（ 1-仅退款 2-退货退款），退款类型（退款类型 1-售中 2-售后）
        //     * 下单人（对应member表的id）,下单人头像，下单人昵称，下单人姓名，退款单ID
        Consultations consultations =
                setConsultations(param.getOrderInfoId(), param.getImage1(),param.getImage2(),param.getImage3(),param.getImage4(),
                        refundMoney, param.getApplyQtys(),param.getReasons(),param.getRemark(),
                        param.getServiceType(),refundType,
                        platConsumerRs.getData().getMemberId(),
                memberRs.getData().getAvatar(),memberRs.getData().getNickName(),memberRs.getData().getRealName(),
                refundOrderRs.getData().getId());
        Response<Consultations> consultationsRs = orderFeignService.saveConsultations(consultations);
        if (null == consultationsRs || consultationsRs.getCode() != 200 || null == consultationsRs.getData()) {
            return Response.failed("新增退款单协商历史失败");
        }

        Consultations consultations2 = setSysConsu(param.getOrderInfoId(), refundOrderRs.getData().getId(),"等待商家处理申请",
                "若商家在3日内未处理，系统将自动同意退款");
        Response<Consultations> consultationsRs2 = orderFeignService.saveConsultations(consultations2);
        if (null == consultationsRs2 || consultationsRs2.getCode() != 200 || null == consultationsRs2.getData()) {
            return Response.failed("新增退款单协商历史失败");
        }

        OrderInfoUpdateParam orderInfoParam = new OrderInfoUpdateParam();
        orderInfoParam.setId( orderInfo.getId());
        orderInfoParam.setServiceStatus(OrderInfoServiceStatusEnum.IN_THE_AFTER_SALE.getCode());
        Response<Boolean> orderInfoUpRs =  orderFeignService.updateOrderInfoById(orderInfoParam);
        if (null == orderInfoUpRs || orderInfoUpRs.getCode() != 200 || null == orderInfoUpRs.getData()) {
            return Response.failed("更新子订单为售后中状态失败");
        }
        return Response.data(refundOrderRs.getData().getId());
    }

    private Consultations setSysConsu(Long orderInfoId, Long refundId,String title,String msg) {
        Consultations consultations2 = new Consultations();
        consultations2.setSubId(orderInfoId);
        consultations2.setRefundId(refundId);
        consultations2.setStatus(RefundOrderStatusEnum.SYS_RECORD.getCode());
        Map<String,Object> map2 = new HashMap<>();
        map2.put("avatar","");
        map2.put("nickName","好获严选系统");
        map2.put("realName","");
        map2.put("title",title);
        map2.put("msg",msg);
        map2.put("userType",2);
        consultations2.setRemark(JSONObject.toJSONString(map2));
        return consultations2;
    }

    /**
     * @Author qry
     * @Date 14:27 2019/8/28
     * 子订单id ,图1,图2,图3,图4，
     * 退款金额，退款数量，退款原因，退款说明
     * 服务类型（ 1-仅退款 2-退货退款），退款类型（退款类型 1-售中 2-售后）
     * 下单人（对应member表的id）,下单人头像，下单人昵称，下单人姓名，退款单ID
     **/
    private Consultations setConsultations(Long orderInfoId,String img1,String img2,String img3,String img4,
            BigDecimal refundAmount,Long applyQtys,String reasons,String remark,
               Integer serviceType,Integer refundType,
              Long memberId, String avatar,String nickName,String realName,Long refundId) {
        Consultations consultations = new Consultations();
        consultations.setSubId(orderInfoId);
        consultations.setRefundId(refundId);
        consultations.setStatus(RefundOrderStatusEnum.WAIT_SELLER_HANDLE.getCode());
        List<String> images = new ArrayList<>();
        if(StringUtils.isNotBlank(img1)){
            images.add(img1) ;
        }
        if(StringUtils.isNotBlank(img2)){
            images.add(img2) ;
        }
        if(StringUtils.isNotBlank(img3)){
            images.add(img3) ;
        }
        if(StringUtils.isNotBlank(img4)){
            images.add(img4) ;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("avatar",avatar);
        map.put("nickName",nickName);
        map.put("realName",realName);
        map.put("title","买家提交了退款申请");
        map.put("serviceType", RefundServiceTypeEnum.getRefundServiceType(serviceType));
        map.put("qty", applyQtys);
        map.put("reason",reasons );
        map.put("money",refundAmount);
        map.put("coin","0");
        map.put("remark",remark);
        map.put("imgaes",images);
        map.put("userType",0);
        consultations.setRemark(JSONObject.toJSONString(map));
        consultations.setImage1(img1);
        consultations.setImage2(img2);
        consultations.setImage3(img3);
        consultations.setImage4(img4);
        consultations.setRefundAmount(refundAmount);
        consultations.setRefundType(refundType);
        consultations.setRefundCoines(0L);
        consultations.setServiceType(serviceType);
        consultations.setUserId(memberId);
        consultations.setReasons(reasons);
        return consultations;
    }


    /**
     * 退款取消
     * @param param 退款取消
     * @return Response
     */
    @PutMapping("/refundCancel")
    @ApiOperation(value = "退款取消", notes = "退款取消", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response refundCancel(@RequestBody @Valid RefundOrderCancelParam param) {
        return Response.data(shxpRefundOrderService.refundCancel(param));

    }

    /**
     * 退款被拒绝后重新发起的退款申请
     * @param param 退款申请
     * @return Response
     */
    @PutMapping("/refundReApply")
    @ApiOperation(value = "退款被拒绝后重新发起的退款申请", notes = "退款被拒绝后重新发起的退款申请", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response refundReApply(@RequestBody @Valid RefundOrderReApplyParam param) {
        Response<RefundOrder> refundOrderRs = orderFeignService.getRefundOrderById(param.getRefundId());
        if (null == refundOrderRs || refundOrderRs.getCode() != 200 || null == refundOrderRs.getData()) {
            return Response.failed("获取退款单信息失败");
        }
        RefundOrder refundOrder = refundOrderRs.getData();

        Response<MemberDto> memberRs = userFeignService.getMemberById(refundOrder.getUserId());
        if (null == memberRs || memberRs.getCode() != 200 || null == memberRs.getData()) {
            return Response.failed("获取下单消费者失败");
        }
        Response<OrderInfo> orderInfoRs =  orderFeignService.getOrderInfoById(refundOrder.getSubId());
        if (null == orderInfoRs || orderInfoRs.getCode() != 200 || null == orderInfoRs.getData()) {
            return Response.failed("未获取到子订单信息");
        }
        OrderInfo orderInfo = orderInfoRs.getData();
        BigDecimal refundMoney = orderInfo.getAmount().divide(new BigDecimal(orderInfo.getQuantity())) .multiply(new BigDecimal(param.getApplyQtys()));

        refundOrder.setApplyQtys(param.getApplyQtys());
        refundOrder.setRefundAmount(refundMoney);
        refundOrder.setRefundCoines(0L);
        refundOrder.setStatus(RefundOrderStatusEnum.WAIT_SELLER_HANDLE.getCode());
        refundOrder.setServiceType(param.getServiceType());
        refundOrder.setRefundType(param.getRefundType());
        refundOrder.setReasons(param.getReasons());
        refundOrder.setRemark(param.getRemark());
        Response<Boolean> rs = orderFeignService.updataRefundOrderById(refundOrder);
        if (null == rs || rs.getCode() != 200) {
            return rs;
        }

        //* 子订单id ,图1,图2,图3,图4，
        //     * 退款金额，退款数量，退款原因，退款说明
        //     * 服务类型（ 1-仅退款 2-退货退款），退款类型（退款类型 1-售中 2-售后）
        //     * 下单人（对应member表的id）,下单人头像，下单人昵称，下单人姓名，退款单ID
        Consultations consultations = setConsultations(refundOrder.getSubId(), param.getImage1(),param.getImage2(),
                param.getImage3(),param.getImage4(),refundMoney,param.getApplyQtys(),
                param.getReasons(),param.getRemark(),param.getServiceType(),param.getRefundType(),
                refundOrder.getUserId(), memberRs.getData().getAvatar(),memberRs.getData().getNickName(),
                memberRs.getData().getRealName(), param.getRefundId());
        Response<Consultations> consultationsRs = orderFeignService.saveConsultations(consultations);
        if (null == consultationsRs || consultationsRs.getCode() != 200 || null == consultationsRs.getData()) {
            return Response.failed("新增退款单协商历史失败");
        }

        //删除旧的 系统协商历史记录
        Response<Boolean> consultationsDeleteRs = orderFeignService.deletePhysicConsultations(param.getRefundId());
        if (null == consultationsDeleteRs || consultationsDeleteRs.getCode() != 200 || null == consultationsDeleteRs.getData()) {
            return Response.failed("删除退款单协商历史系统记录失败");
        }

        //新增 新系统协商历史记录
        Consultations consultations2 = setSysConsu(refundOrder.getSubId(), refundOrderRs.getData().getId(),
                "等待商家处理申请","若商家在3日内未处理，系统将自动同意退款");
        Response<Consultations> consultationsRs2 = orderFeignService.saveConsultations(consultations2);
        if (null == consultationsRs2 || consultationsRs2.getCode() != 200 || null == consultationsRs2.getData()) {
            return Response.failed("新增退款单协商历史失败");
        }

        OrderInfoUpdateParam orderInfoParam = new OrderInfoUpdateParam();
        orderInfoParam.setId( refundOrder.getSubId());
        orderInfoParam.setServiceStatus(OrderInfoServiceStatusEnum.IN_THE_AFTER_SALE.getCode());
        Response<Boolean> orderInfoUpRs =  orderFeignService.updateOrderInfoById(orderInfoParam);
        if (null == orderInfoUpRs || orderInfoUpRs.getCode() != 200 || null == orderInfoUpRs.getData()) {
            return Response.failed("更新子订单为售后中状态失败");
        }
        return Response.data(true);

    }


    @ApiOperation(value = "子订单详情 -- 退款单列表和详情")
    @GetMapping("/refundDetail/{subId}")
    public Response<List<RefundDetailVo>> refundDetail(@PathVariable("subId") Long subId) {
        RefundOrderListParam refundOrderListParam = new RefundOrderListParam();
        refundOrderListParam.setSubId(subId);
        Response<List<RefundOrderVo>> refundOrderListRs  = orderFeignService.listRefundOrder(refundOrderListParam);
        if (null == refundOrderListRs || refundOrderListRs.getCode() != 200 || null == refundOrderListRs.getData()) {
            return Response.failed("获取子订单下的退款单失败");
        }
        List<Long> listRefundOrderIds = refundOrderListRs.getData().stream().map(RefundOrderVo::getId).collect(Collectors.toList());

        Response<List<Consultations>> conListRs = orderFeignService.listConsultationsByRefundIds(listRefundOrderIds);
        if (null == conListRs || conListRs.getCode() != 200 || null == conListRs.getData()) {
            return Response.failed("获取协商历史失败");
        }
        Map<String,List<Consultations>> map = new HashMap<>();
        Set<Long> idssss= new HashSet<>();
        List<Consultations> temp = new ArrayList<>();
        for (Consultations c : conListRs.getData() ){
            if(!idssss.contains(c.getRefundId())){
                temp = new ArrayList<>();
                idssss.add(c.getRefundId());
                map.put(c.getRefundId().toString(),temp);
            }
            temp.add(c);
        }
        idssss = null;
        idssss.clear();
        List<RefundDetailVo> rs = new ArrayList<>();
        for (RefundOrderVo v: refundOrderListRs.getData()){
            RefundDetailVo vo = new RefundDetailVo();
            vo.setRefundOrder(v);
            vo.setListHistory(map.getOrDefault(v.getId().toString(),new ArrayList<>()));
        }
        return Response.data(rs);
    }

    @ApiOperation(value = "退款售后-退款单分页列表")
    @PostMapping("/pageRefundOrder")
    public Response<Page<RefundOrderVo>> pageRefundOrder(@RequestBody @Valid RefundPageParam param) {
        Response<ConsumerDto> platConsumerRs = userFeignService.getConsumerById(param.getUserId());
        if (null == platConsumerRs || platConsumerRs.getCode() != 200 || null == platConsumerRs.getData()) {
            return Response.failed("下单消费者不存在");
        }

        RefundOrderPageParam paramP = new RefundOrderPageParam();
        paramP.setUserId(platConsumerRs.getData().getMemberId());
        paramP.setPageNumber(param.getPageNumber());
        paramP.setPageSize(param.getPageSize());
        Response<Page<RefundOrderVo>>  refundOrderVoRs = orderFeignService.pageRefundOrder(paramP);
        if (null == refundOrderVoRs || refundOrderVoRs.getCode() != 200 || null == refundOrderVoRs.getData()) {
            return Response.failed("获取退款单列表失败");
        }

        if(refundOrderVoRs.getData().getRecords().size() == 0){
            return refundOrderVoRs;
        }

        Set<Long> orderInfoIds = refundOrderVoRs.getData().getRecords().stream().map(RefundOrderVo::getSubId).collect(Collectors.toSet());
        List<Long> orderInfoIdss = new ArrayList<>(orderInfoIds);
        Response<List<OrderInfo>> orderInfoListRs = orderFeignService.getOrderInfoByIds(orderInfoIdss);
        if (null == orderInfoListRs || orderInfoListRs.getCode() != 200 || null == orderInfoListRs.getData()) {
            return Response.failed("获取退款单对应的子订单列表失败");
        }

        Set<Long> platStoreIds = orderInfoListRs.getData().stream().map(OrderInfo::getStoreId).collect(Collectors.toSet());
        List<Long> platStoreIdss = new ArrayList<>(platStoreIds);

        Response<List<PlatStore>> platStoreListRs = userFeignService.getPlatStoreByIds(platStoreIdss);
        if (null == platStoreListRs || platStoreListRs.getCode() != 200 || null == platStoreListRs.getData()) {
            return Response.failed("获取退款单对应的子订单的店铺列表失败");
        }

        Map<String,String> storeMap = new HashMap<>();
        for(PlatStore st : platStoreListRs.getData()){
            storeMap.put(st.getId().toString(),st.getStoreName());
        }
        Map<String,String> orderInfoMap = new HashMap<>();
        for(OrderInfo oi: orderInfoListRs.getData()){
            orderInfoMap.put(oi.getId().toString(),storeMap.get(oi.getStoreId().toString()));
        }
        for(RefundOrderVo vo : refundOrderVoRs.getData().getRecords()){
            vo.setStoreName(orderInfoMap.get(vo.getSubId().toString()));
        }
        return  refundOrderVoRs;
    }

    @ApiOperation(value = "退款单详情")
    @GetMapping("/refundDetail2/{refundId}")
    public Response<RefundDetailVo> refundDetail2(@PathVariable("refundId") Long refundId) {
        RefundDetailVo rs = new RefundDetailVo();
        Response<RefundOrder> refundOrderRs  = orderFeignService.getRefundOrderById(refundId);
        if (null == refundOrderRs || refundOrderRs.getCode() != 200 || null == refundOrderRs.getData()) {
            return Response.failed("获取子订单下的退款单失败");
        }
        Response<List<Consultations>> conListRs = orderFeignService.listConsultationsByRefundId(refundId);
        RefundOrderVo rovo ;
        try{
            rovo = BeanUtils.covertType(refundOrderRs.getData(), RefundOrderVo.class);
        }catch (Exception e){
           return Response.failed("新增订单信息异常");

        }
        rovo.setServiceTypeCn(RefundServiceTypeEnum.getRefundServiceType(rovo.getServiceType()));
        rovo.setRefundTypeCn(RefundTypeEnum.getRefundTypeType(rovo.getRefundType()));
        rovo.setStatusCn(RefundOrderStatusEnum.getStatusCn(rovo.getStatus()));
        rs.setListHistory(conListRs.getData());
        rs.setRefundOrder(rovo);
        return Response.data(rs);
    }


    @ApiOperation("申请售后页面数据")
    @GetMapping("/applyAfterSaleInfo/{subId}")
    public Response<ApplyAfterSaleInfoVo> applyAfterSaleInfo(@PathVariable("subId") Long subId){

        ApplyAfterSaleInfoVo rs = new ApplyAfterSaleInfoVo();
        Response<OrderInfo> orderInfoRs =  orderFeignService.getOrderInfoById(subId);
        if (null == orderInfoRs || orderInfoRs.getCode() != 200 || null == orderInfoRs.getData()) {
            return Response.failed("未获取到子订单信息");
        }
        OrderInfo orderInfo = orderInfoRs.getData();
        BigDecimal perMoney = orderInfo.getAmount().divide(new BigDecimal(orderInfo.getQuantity()));

        RefundOrderListParam refundOrderListParam = new RefundOrderListParam();
        refundOrderListParam.setNeStatus( RefundOrderStatusEnum.REFUND_CANCEL.getCode());
        refundOrderListParam.setSubId(subId);
        Response<List<RefundOrderVo>> refundOrderListRs  = orderFeignService.listRefundOrder(refundOrderListParam);
        if (null == refundOrderListRs || refundOrderListRs.getCode() != 200 || null == refundOrderListRs.getData()) {
            return Response.failed("获取子订单下的退款单失败");
        }

        Response<ExtSpuDto> extSpuRs = goodsFeignService.getExtSpuById(orderInfo.getSpuId());
        if (null == extSpuRs || extSpuRs.getCode() != 200 || null == extSpuRs.getData()) {
            return Response.failed("未获取订单内的商品信息");
        }

        BigDecimal qtys  = BigDecimal.ZERO;
        for (RefundOrderVo r:refundOrderListRs.getData()){
            qtys = qtys.add(new BigDecimal(r.getApplyQtys()));
        }

        List<String> specList = new ArrayList<>();
        Map<String, Map<String, String>> s = JSONObject.parseObject(orderInfo.getSpuExtendSpec(), Map.class);
        s.forEach((k, value) -> specList.add(s.get(k).get("spec_itemname")));

        //可申请的最大数量
        Long maxQty =  (new BigDecimal(orderInfo.getQuantity()).subtract(qtys)).longValue();

        rs.setSubId(subId);
        rs.setProductTitle(orderInfo.getSpuName());
        rs.setSpecCn(StringUtils.join(specList, "/"));
        rs.setImage(extSpuRs.getData().getSpuImage());
        rs.setQty(orderInfo.getQuantity());
        rs.setApplyMaxQty(maxQty);
        rs.setMoney(perMoney);
        rs.setOrderStatus(orderInfo.getOrderStatus());
        rs.setServiceType(orderInfo.getServiceStatus());
        return Response.data(rs);
    }


}
